<template>
	<view class="addSite">
		<u-navbar back-icon-color="#FFFFFF" :back-text-style="backText" title-color="#FFFFFF" :background="barbg" back-text="返回"
		 title="添加作业点">
			<view class="navbar-right" slot="right" @click="addSite()">确定</view>
		</u-navbar>
		<view class="map">
			<map style="width: 750rpx; height: 700rpx;" id="navmap" :latitude="latitude" :longitude="longitude"
			 :markers="markers" :circles="circles"></map>
		</view>
		<view class="add-box">
			<view class="kong">
				<!-- 				<u-row :gutter="0" class="row1">
					<u-col>
						<u-search placeholder="请输入点位位置"  @search="getMap" v-model="siteLation" shape="square" :show-action="false"></u-search>
					</u-col>
				</u-row> -->
				<!-- <view>{{form.latitude}} {{form.longitude}}</view> -->
				<u-row :gutter="0" class="row2">
					<u-col :span="6">
						有效半径
					</u-col>
					<u-col :span="6" style="text-align: right;">
						{{silderValue}} M
					</u-col>
				</u-row>
				<u-row :gutter="0" class="row3">
					<u-col>
						<u-slider v-model="silderValue" min="5" max="100"></u-slider>
					</u-col>
				</u-row>
			</view>
			<u-form :model="form" ref="uForm">
				<u-form-item label-width="130" label="点位名称" prop="name">
					<u-input v-model="form.name" placeholder="请输入点位名称" />
				</u-form-item>
				<!-- 				<u-form-item label-width="130" label="联系人" prop="contact">
					<u-input v-model="form.contact" placeholder="请输入联系人姓名" />
				</u-form-item>
				<u-form-item label-width="130" label="电话" prop="contactPhone">
					<u-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
				</u-form-item> -->
				<u-form-item label-width="130" label="联系人">
					<u-input v-model="form.contact" type="select" placeholder="请选择点位联系人" @tap="selectUserShow = true"></u-input>
				</u-form-item>
				<u-form-item label-width="130" label="点位类型">
					<u-input v-model="siteType" type="select" placeholder="请选择点位类型" @tap="selectShow = true"></u-input>
				</u-form-item>
				<!-- 启用地图定位 -->
				<!-- 				<u-form-item label-width="130" label="经度" prop="longitude">
					<u-input v-model="form.longitude" placeholder="请输入点位经度" type="number" />
				</u-form-item>
				<u-form-item label-width="130" label="纬度" prop="latitude">
					<u-input v-model="form.latitude" placeholder="请输入点位纬度" type="number" />
				</u-form-item>
				<u-form-item label-width="130" label="范围" prop="scope">
					<u-input v-model="form.scope" placeholder="请输入点位范围" type="number" />
				</u-form-item> -->
				<!-- 弹出地图插件 -->
				<!-- <selectMap></selectMap> -->

			</u-form>
		</view>
		<!-- 		<view class="button-box">
			<u-button type="primary" @tap="addSite">添加</u-button>
		</view> -->
		<view class="nav" v-show="isclick">
			<navigator url="/pages/root/user/addUser/index" hover-class="navigator-hover">
				<view>没有负责人？前往添加 &nbsp; <u-icon name="arrow-right"></u-icon>
				</view>
			</navigator>
		</view>
		<u-select mode="single-column" :list="selectList" v-model="selectShow" @confirm="selectConfirm"></u-select>
		<u-select mode="single-column" :list="selectUserList" v-model="selectUserShow" @confirm="selectUserConfirm"></u-select>
	</view>
</template>

<script>
	import {
		createSite,
		getSite
	} from "@/api/site.js"
	import {
		getUserInfo
	} from "@/api/user.js"
	import selectMap from "@/components/selectMap.vue"
	import {
		queryParams,
		checkOpenGPSServiceByAndroid,
		gcjToGps,
		gpsToGcj
	} from "@/common/index.js"
	const leleLocation = uni.requireNativePlugin('Lele-Location');
	let _self = null
	export default {
		data() {
			return {
				form: {
					name: '',
					type: '',
					contactPhone: '',
					contact: '',
					longitude: null,
					latitude: null,
					scope: null,
					projectId: null
				},
				barbg: {
					background: '#5c92ff'
				},
				backText: {
					color: '#FFFFFF'
				},
				isclick: false,
				siteLation: null,
				siteType: '',
				selectShow: false,
				selectUserShow: false,
				silderValue: 5,
				valuedata: 0,
				timeAndroid: null,
				rules: {
					password: [{
						required: true,
						message: '请输入密码',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}, {
						min: 6,
						message: '密码长度不能少于6位',
						trigger: 'blur'
					}, {
						max: 16,
						message: '密码长度不能多于16位',
						trigger: 'blur'
					}],
					name: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					longitude: [{
						required: true,
						message: '不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					latitude: [{
						required: true,
						message: '不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					scope: [{
						required: true,
						message: '请输入范围',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					siteType: [{
						required: true,
						message: '不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					contact: [{
						required: true,
						message: '请正确输入',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					contactPhone: [{
						required: true,
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// this.$u.test.mobile()就是返回true或者false的
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: 'blur',
					}],
				},
				selectUserList: [],
				selectList: [{
						value: '1',
						label: '作业点'
					},
					{
						value: '2',
						label: '卸土点'
					},

				],
				timer: null,
				// 地图
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 39.909,
				longitude: 116.39742,
				circles: [{}], //圆
				markers: [{}],
				// 高德地址转化
				// mapUrl: "https://restapi.amap.com/v3/geocode/geo",
				parameters: {
					address: "重庆工业职业学院",
					key: "01849cc031d462fa1bb5c22f39c51c4d",
					output: "JSON"
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
			var nmap = uni.createMapContext("navmap", this).$getAppMap();
			nmap.onclick = (res) => {
				// this.markers = [{
				// 	id: 1,
				// 	latitude: res.latitude,
				// 	longitude: res.longitude,
				// 	iconPath: '../../../../static/positionRed.png',
				// }];
				this.markers.forEach((item, index) => {
					if (item.id === 0) {
						this.markers[index].latitude = res.latitude
						this.markers[index].iconPath = '/static/positionRed.png'
						this.markers[index].longitude = res.longitude

						this.circles[index].radius = this.silderValue
						this.circles[index].latitude = res.latitude
						this.circles[index].longitude = res.longitude
					}
				})

				this.latitude = res.latitude
				this.longitude = res.longitude
				this.form.latitude = res.latitude
				this.form.longitude = res.longitude
			}
			// console.log(uni.getStorageSync('id'))
		},
		created() {
			this.getuser()
			this.getSiteData() //获取已有的点位
			checkOpenGPSServiceByAndroid() //判断是否打开了定位
			if (uni.getSystemInfoSync().platform == "android") {
				this.getLocationPermission()
			}
			if (uni.getSystemInfoSync().platform == "ios") {
				this.getLocationInfo() //获取当前位置
			}
			// this.getMap()	

		},
		onShow() {
			var pages = getCurrentPages();
			// this.getLocationInfo() //获取当前位置
			this.prevPage = pages[pages.length - 1];
			if (this.prevPage.brand === true) {
				this.getuser()
			}
		},
		destroyed() {
			clearInterval(this.timer)
			clearInterval(this.timeAndroid)
		},
		components: {
			selectMap: selectMap
		},
		watch: {
			silderValue: {
				handler(newVal, oldVal) {
					this.valuedata = newVal
					// this.circles[0].radius = this.silderValue
					this.circles[0].radius = newVal
					this.form.scope = newVal
				},
				immediate: false
			},
		},
		methods: {
			getLocationPermission() {
				_self = this
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						uni.getSystemInfo({
							success: function(res) {
								if (res.platform === "android") {
									uni.showToast({
										title: '地位服务'
									})
									_self.location()
								}
							}
						});
					}
				});
			},
			location() {
				//开始定位
				leleLocation.location({
						intervalTime: 2000, //可选，间隔定位时间，单位毫秒(ms)，默认2000ms。
						isSendUp: false, //是否需要上送到业务服务器
						isShowNotify: true, //是否在通知栏显示"定位中..."的提示
						notifyTip: '工作中...', //通知栏提示信息，默认为"定位中..."
						isPermanent: true, //是否常驻通知栏(常驻通知栏，点击不会取消)，isShowNotify参数为true时才有效。
						isStartApp: false ////点击通知栏定位提示是否启动app，默认启动。传入false时，点击通知栏提示将无任何反应。
					},
					result => {
						const resJson = JSON.stringify(result);
						switch (result.code) {
							case '0':
								let info = JSON.parse(result.msg)
								let marker = {
									id: 0,
									latitude: info.latitude,
									longitude: info.longitude,
									iconPath: '/static/positionRed.png',
									label: {
										content: "当前位置"
									}
								};
								let circle = { //在地图上显示圆
									latitude: info.latitude,
									longitude: info.longitude,
									fillColor: "#66666666", //填充颜色
									color: "#A7B6CB", //描边的颜色
									radius: this.valuedata, //半径
									strokeWidth: 2 //描边的宽度
								};
								this.latitude = info.latitude
								this.longitude = info.longitude
								this.form.latitude = info.latitude
								this.form.longitude = info.longitude
								
								this.markers[0] = marker
								this.circles[0] = circle
								
								// _self.latitude = info.latitude
								// _self.longitude = info.longitude
								// _self.covers[0].latitude = info.latitude;
								// _self.covers[0].longitude = info.longitude;
								// console.log(_self.latitude,_self.longitude) 
								// console.log('callback---sendContent--' + result.sendContent);
								break;
							case '-1':
								console.log('callback---button--' + result.msg.latitude);
								break;
						}
					}
				);
			},
			// 选择商品类型回调
			selectConfirm(e) {
				this.form.type = '';
				// console.log(e)
				e.map((val, index) => {
					this.siteType = val.label
					this.form.type = val.value
				});
			},
			selectUserConfirm(e) {
				e.map((val, index) => {
					// console.log(val)	
					this.form.contact = val.label
					this.form.contactPhone = val.value
				});
			},
			getSiteData() {
				this.markers = []
				this.circles = []
				getSite({
					projectId: uni.getStorageSync('id')
				}).then(res => {
					// console.log(res)
					if (res.code !== 1) {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
						return
					}
					res.result.forEach((item, index) => {
						let map = {
							iconPath: "/static/positionone.png",
							title: item.name,
							width: "30px",
							height: "30px",
							label: {
								content: item.name
							},
						}
						if (item.type === '1') {
							map.iconPath = "/static/positionGreen.png"
						} else if (item.type === '2') {
							map.iconPath = "/static/positionYellow.png"
						}
						// console.log(item)
						let cir = {
							fillColor: "#4C4C4C4C", //填充颜色
							color: "#A7B6CB", //描边的颜色
							radius: 50, //半径
							strokeWidth: 2
						}
						let pos = gpsToGcj(item.longitude, item.latitude)
						map.id = index + 1
						map.latitude = pos[1]
						map.longitude = pos[0]

						cir.latitude = pos[1]
						cir.longitude = pos[0]
						cir.radius = item.scope
						
						this.markers.push(map)
						this.circles.push(cir)
					})
				})
				// console.log(this.circles)
			},
			getuser() {
				this.selectUserList = []
				getUserInfo({
					roleId: 2
				}).then(res => {
					// console.log(res)
					if (res.code !== 1) {
						uni.showToast({
							title: "数据获取失败",
							icon: "none"
						})
						return
					}
					if (res.result.length === 0) {
						// console.log("没有东西")
						this.isclick = true
						return
					}
					for (let index in res.result) {
						let lemp = {}
						lemp.label = res.result[index].name
						lemp.value = res.result[index].phone
						this.selectUserList.push(lemp)
					}
				})
			},
			addSite() {
				if (this.isclick) {
					return
				}
				this.form.projectId = uni.getStorageSync('id')
				if (!this.form.longitude || !this.form.latitude || !this.form.scope) {
					uni.showToast({
						title: "请检查定位或点位范围",
						icon: "none"
					})
					return
				}
				this.$refs.uForm.validate(val => {
					if (val) {
						let pos = gcjToGps(this.form.longitude, this.form.latitude)
						this.form.longitude = pos[0]
						this.form.latitude = pos[1]
						createSite(this.form).then(res => {
							console.log(res)
							uni.showToast({
								title: res.msg,
								icon: "none",
								duration: 2000
							})
							if (res.code !== 1) {
								return
							}
							setTimeout(() => {
								var item = true; //item为要传的值
								var pages = getCurrentPages();
								var prevPage = pages[pages.length - 2];
								prevPage.brand = item;
								uni.navigateBack()
							}, 500)
							// console.log(res)
							// setTimeout(() =>{
							// 	uni.navigateTo({
							// 		url: '/pages/project/user/index'
							// 	})
							// },2000)
						}).catch(err => {
							console.log("出错了")
							console.log(err)
						})
					}
				})
			},
			getMap() {
				let mapUrl = "https://restapi.amap.com/v3/geocode/geo"
				if (!!this.siteLation) {
					this.parameters.address = this.siteLation
				}
				// console.log("good!!!")
				mapUrl = mapUrl + queryParams(this.parameters, '?')
				// console.log(this.mapUrl)
				uni.request({
					url: mapUrl,
					method: "GET",
					dataType: 'json',
					success: res => {
						console.log(res)
						if (res.statusCode !== 200) {
							uni.showToast({
								title: "定位失败",
								icon: "none"
							})
							return
						}
						let num = res.data.geocodes[0].location.split(',')
						this.longitude = num[0]
						this.latitude = num[1]
						this.form.longitude = num[0]
						this.form.latitude = num[1]

						// console.log(num)
					}
				})

			},
			// 获取地理位置
			getLocationInfo() {
				var that = this
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						console.log(res);
						clearInterval(that.timer)
						let marker = {
							id: 0,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '/static/positionRed.png',
							label: {
								content: "当前位置"
							}
						};
						let circle = { //在地图上显示圆
							latitude: res.latitude,
							longitude: res.longitude,
							fillColor: "#66666666", //填充颜色
							color: "#A7B6CB", //描边的颜色
							radius: that.valuedata, //半径
							strokeWidth: 2 //描边的宽度
						};

						that.latitude = res.latitude
						that.longitude = res.longitude
						that.form.latitude = res.latitude
						that.form.longitude = res.longitude

						that.markers[0] = marker
						that.circles[0] = circle 
					},
					fail: (err) => {
						uni.showToast({
							title: "定位失败，正在重连...",
							icon: "none"
						})
						console.log(err);
						if (!this.timer) {
							checkOpenGPSServiceByAndroid() //判断是否打开了定位
							this.timer = setInterval(() => {
								this.getLocationInfo()
							}, 3000)
						}
						// checkOpenGPSServiceByAndroid() //判断是否打开了定位
						// setTimeout(() =>{
						// 	this.getLocationInfo()
						// } , 2000)
					}
				});
			},

		}
	};
</script>

<style lang="scss" scoped>
	.navbar-right {
		padding: 0px 40rpx;
		color: #ffffff;
	}

	.addSite {
		// padding: 40rpx;
		background-color: white;
		height: auto;
		min-height: 100%;
		box-sizing: border-box;

		// padding-top: 100rpx;
		.add-box {
			background-color: #ffffff;
			border-radius: 10rpx;
			padding: 40rpx;

			// padding-top: 100rpx;
			// margin-bottom: 160rpx;
			.kong {
				.row1 {
					padding-bottom: 50rpx;
				}

				.row2 {
					padding: 20rpx 0;
					padding-top: 30rpx;

					.u-col {
						font-weight: 550;
						font-size: 31rpx;
					}
				}

				.row3 {
					padding: 30rpx 0;
				}
			}

		}

		.button-box {
			// margin-top: 30rpx;
			padding: 30rpx 0;
			padding: 0 30rpx;
		}
	}

	.nav {
		text-align: center;
		// margin-top: 100rpx;
		line-height: 150rpx;
		color: blue;
	}
</style>
